import { refreshTokenUrl } from "@/common/api/url.js"

let isRefreshing = false
let failedQueue = []

const processQueue = (error) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error)
    } else {
      prom.resolve()
    }
  })
  failedQueue = []
}

const errorInterceptor = (axiosInstance) => (error) => {
  const _axios = axiosInstance
  const originalRequest = error.config
  const status = error.response?.status

  if (status === 409) {
    if (isRefreshing) {
      return new Promise(function(resolve, reject) {
        failedQueue.push({ resolve, reject })
      }).then(() => {
        return _axios(originalRequest)
      }).catch(err => {
        return Promise.reject(err)
      })
    }

    isRefreshing = true
    const refresh_token = uni.getStorageSync('refresh_token')
    if (!refresh_token) {
      throw new axios.Cancel('no refresh_token !')
      //转登录
    }
    return new Promise(function(resolve, reject) {
      _axios.post(refreshTokenUrl, { grant_type: 'grant_type', refresh_token: refresh_token })
        .then(response => {
          const token = response.data.access_token
          uni.setStorageSync('token', token)
          resolve(_axios(originalRequest))
          processQueue()
        }).catch(err => {
          reject(err)
          processQueue(err)
        }).finally(() => { isRefreshing = false })
    })
  }
  
  if (status === 410) {
    let message = "身份信息已过期，请重新登录"
    uni.showToast({ title: message, icon: "none", mask: true, duration: 2000 })
    return Promise.reject(error)
  }
  
  let message = error.response?.data.detail || error.message || "ERROR!"
  if (typeof message == 'object') { message = JSON.stringify(message) }
  uni.showToast({ title: message, icon: "none", mask: true, duration: 10000 })
  return Promise.reject(error)
}

export default errorInterceptor
